﻿using Codemonk.Common.Caching;
using System.Net;

namespace System
{
    public static class StringExtensions
    {
        private static Type STRING_TYPE = typeof(string);
        private static ICacheCollection<string, Type> cache = new DictionaryCache<string, Type>();
        public static T As<T>(this string str, Func<string, T> convert, T defaultValue = default(T))
        {
            if (typeof(T) == STRING_TYPE) return (T)(str as object);
            try
            {
                return convert(str);
            }
            catch
            {
                return defaultValue;
            }
        }
        public static int AsInt(this string str, int defaultValue = 0)
        {
            return As<int>(str, int.Parse, defaultValue);
        }
        public static float AsFloat(this string str, float defaultValue = 0)
        {
            return As<float>(str, float.Parse, defaultValue);
        }
        public static decimal AsDecimal(this string str, decimal defaultValue = 0)
        {
            return As<decimal>(str, decimal.Parse, defaultValue);
        }
        public static IPAddress AsIPAddress(this string str, IPAddress defaultValue = null)
        {
            return As<IPAddress>(str, IPAddress.Parse, defaultValue);
        }
        public static Type AsType(this string str, Type defaultValue = null)
        {
            Type type;
            if (cache.TryGet(str, out type)) return type;
            type = As<Type>(str, Type.GetType, defaultValue);
            cache.Set(str, type);
            return type;
        }
    }
}
